package curd;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class StudentManager {
	final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	// 查找指定性别的所有学生信息
	public List<Student> readFromXml(String sexa) {
		List<Student> list = new ArrayList<Student>();
		Document doc = null;
		SAXReader saxReader = new SAXReader();
		try {
			// 读取文件，能用相对目录劲量用
			doc = saxReader.read(new File("java.xml"));
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		// 通过Document和根节点查找方式 是不同的
		Element root = doc.getRootElement();
		// System.out.println("student[@sex=\"" + sexa + "\"]");
		List<Element> l2 = root.selectNodes("student[@sex=\"" + sexa + "\"]");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		for (Element e : l2) {
			String sex = e.attributeValue("sex");
			String name = e.selectSingleNode("name").getText();
			String school = e.selectSingleNode("school").getText();
			String birth = e.selectSingleNode("birth").getText();
			Date date = null;
			try {
				date = df.parse(birth);
			} catch (ParseException e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
			Student st = new Student(sex, name, school, date);
			list.add(st);
		}
		return list;
	}

	public List<Student> readFromXml() {
		List<Student> list = new ArrayList<Student>();
		Document doc = null;
		SAXReader saxReader = new SAXReader();
		try {
			// 读取文件，能用相对目录劲量用
			doc = saxReader.read(new File("java.xml"));
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		Element root = doc.getRootElement();
		List<Element> l2 = root.selectNodes("student");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		for (Element e : l2) {
			String sex = e.attributeValue("sex");
			String name = e.selectSingleNode("name").getText();
			String school = e.selectSingleNode("school").getText();
			String birth = e.selectSingleNode("birth").getText();
			Date date = null;
			try {
				date = df.parse(birth);
			} catch (ParseException e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
			Student st = new Student(sex, name, school, date);
			list.add(st);
		}
		return list;
	}

	/**
	 * 根据姓名，修改对应的学校
	 * 
	 * @param name
	 * @param schoolName
	 * @return
	 */
	public boolean update(String stname, String schoolName) {

		Document doc = null;
		SAXReader saxReader = new SAXReader();
		try {
			// 读取文件，能用相对目录劲量用
			doc = saxReader.read(new File("java.xml"));
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		Element root = doc.getRootElement();
		List<Element> l2 = root.selectNodes("student");

		for (Element e : l2) {

			String name = e.selectSingleNode("name").getText();
			if (stname.equals(name)) {// 找到了这个学生
				Element es = (Element) e.selectSingleNode("school");
				es.setText(schoolName);// 修改节点值

				// 保存document对象到文件中
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("utf-8");
				try {
					XMLWriter xm = new XMLWriter(new FileOutputStream(
							"java.xml"), format);
					xm.write(doc);
					xm.close();
				} catch (Exception e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				}
				return true;
			}

		}

		return false;
	}

	// 通过学生姓名修改学校和性别
	public boolean update2(String name, String sex, String school, Date d) {
		Document doc = null;
		try {
			doc = new SAXReader().read(new File("java.xml"));
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return false;
		}

		Element e = (Element) doc.selectSingleNode("/classes/student[name=\""
				+ name + "\"]");
		if (e == null)
			return false;
		e.selectSingleNode("school").setText(school);
		// e.setAttributeValue("sex", sex);
		e.attribute("sex").setValue(sex);
		// 写回去
		e.selectSingleNode("birth").setText(df.format(d));
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		try {
			XMLWriter xm = new XMLWriter(new FileOutputStream("java.xml"),
					format);
			xm.write(doc);
			xm.close();
		} catch (Exception e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}
		return true;
	}

	// 根据学生姓名删除学生
	public boolean delete(String name) {
		Document doc = null;
		try {
			doc = new SAXReader().read(new File("java.xml"));
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return false;
		}
		Element e = (Element) doc.selectSingleNode("/classes/student[name=\""
				+ name + "\"]");
		if (e == null)
			return false;
		e.getParent().remove(e);// !!!!!!!!!!!!!!!
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		try {
			XMLWriter xm = new XMLWriter(new FileOutputStream("java.xml"),
					format);
			xm.write(doc);
			xm.close();
		} catch (Exception e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}
		return true;
	}

	public void add(Student st) {
		Document doc = null;
		try {
			doc = new SAXReader().read(new File("java.xml"));
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return;
		}
		//
		Element root = doc.getRootElement();
		Element newStu = root.addElement("student");
		newStu.addAttribute("sex", st.getSex());
		newStu.addElement("name").setText(st.getName());
		newStu.addElement("school").setText(st.getSchool());
		newStu.addElement("birth").setText(df.format(st.getBirth()));

		// Element e2=newStu.addElement("school");
		// e2.addElement("");
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		try {
			XMLWriter xm = new XMLWriter(new FileOutputStream("java.xml"),
					format);
			xm.write(doc);
			xm.close();
		} catch (Exception e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}
	}

	public static void main(String[] args) throws ParseException {
		StudentManager sm = new StudentManager();
		Scanner sc = new Scanner(System.in);
		Student st = new Student();
		// System.out.println("请输入姓名：");
		// st.setName(sc.next());
		// System.out.println("请输入性别");
		// st.setSex(sc.next());
		// System.out.println("请输入毕业学校：");
		// st.setSchool(sc.next());
		// System.out.println("请输入生日：");
		// st.setBirth(df.parse(sc.next()));
		//
		// sm.add(st);

		// List<Student> li = sm.readFromXml("男");
		List<Student> li = sm.readFromXml();
		for (Student s : li) {
			System.out.println(s);
		}
		// sm.update("蔡启明", "美国加州理工学院合肥分校");
		Date d = df.parse("2017-10-1");
		boolean f = sm.update2("马超", "得", "淮 院", d);
		System.out.println("修改的结果：" + f);
		// boolean del = sm.delete("张洋");
		// System.out.println(del);

		// List<Student> list = sm.readFromXml();
		// for (Student s : list) {
		// System.out.println(s);
		// }
	}
}
